import time
import json
from typing import Any, Dict, Optional
from intelli_port.commons.logging import json_logger, emit_to_elastic
from intelli_port.data_layer.clients import mysql_execute_write
from intelli_port.commons.observability import audit_write_failures_total, audit_write_total, confirm_prompts_total, exec_success_total

def audit_event(action: str, resource: str, intent: str, slots: Dict[str, Any] | None = None, user_id: str | None = None, amount: float | None = None, currency: str | None = None, result: str | None = None, error: str | None = None, corr_id: str | None = None, req_id: str | None = None, device_id: str | None = None, risk_score: float | None = None, risk_flags: Dict[str, Any] | None = None, policy_version: str | None = None, decision: str | None = None, reason_codes: list[str] | None = None, txn_id: str | None = None, tool_name: str | None = None) -> None:
    logger = json_logger()
    event = {
        "ts": int(time.time() * 1000),
        "action": action,
        "resource": resource,
        "intent": intent,
        "slots": slots or {},
        "user_id": user_id or "",
        "amount": amount,
        "currency": currency,
        "result": result,
        "error": error,
        "corr_id": corr_id or "",
        "req_id": req_id or "",
        "device_id": device_id or "",
        "risk_score": risk_score,
        "risk_flags": risk_flags or {},
        "policy_version": policy_version or "",
        "decision": decision or "",
        "reason_codes": reason_codes or [],
        "txn_id": txn_id or "",
        "tool_name": tool_name or "",
    }
    logger.info("audit", extra={"service": "api", "event": json.dumps(event, ensure_ascii=False)})
    emit_to_elastic(event)

def write_ops_log(level: str, message: str, context: Dict[str, Any] | None = None) -> None:
    ctx = json.dumps(context or {}, ensure_ascii=False)
    try:
        mysql_execute_write("INSERT INTO ops_logs(level, message, context, created_at) VALUES(%s,%s,%s,NOW())", (level, message, ctx))
        audit_write_total.inc()
    except Exception:
        audit_write_failures_total.inc()